package com.example.springbasicstudy.transaction.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springbasicstudy.transaction.domain.Transaction;
import com.example.springbasicstudy.transaction.mapper.TransactionMapper;
import com.example.springbasicstudy.transaction.service.TransactionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author li290
 * @description 针对表【transaction(spring事务传播机制)】的数据库操作Service实现
 * @createDate 2022-08-25 20:09:07
 */
@Service
@Slf4j
public class TransactionServiceImpl extends ServiceImpl<TransactionMapper, Transaction>
        implements TransactionService {

    /**
     * 本类方法互相调用导致AOP失效的解决办法：
     *
     * @see README.md:31
     */
    @Lazy
    @Resource
    TransactionService transactionService;
    @Resource
    TransactionMapper transactionMapper;

    /**
     * <a href="https://www.cnblogs.com/jeremylai7/p/15816290.html">事务传播机制博客</a>
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void mainTest() {
        A();

        // 方法2
        // ((TransactionServiceImpl) AopContext.currentProxy()).childTest();
        //方法1 使用接口调本类方法（推荐）
        try {
            transactionService.childTest();
        } catch (Exception e) {
            log.error("exception has been caught");
        }

    }

    @Transactional(propagation = Propagation.NESTED)//事务管理默认只回滚运行时异常
    public void childTest() {
        B();
        throw new RuntimeException();

    }

    //================辅助方法============================
    public void A() {
        transactionMapper.updatePlusOne("a");
    }

    public void B() {
        transactionMapper.updatePlusOne("b");
    }

}




